<style lang="scss" scoped>
.menuInfo-right-top {
  height: 32px;
}

.menuInfo-right-table {
  height: calc(100% - 32px);
}
</style>
<template>
  <div class="app-container-cust">
    <div style="display: flex; height: 100%">
      <div
        :style="{ width: leftSideWidth, overflowX: overflowX }"
        class="left-side"
      >
        <div v-show="leftSide" class="menu-tree">
          <div class="nav">
            <div class="tit-txt">租户机构</div>
            <div>
              <svg-icon
                icon-class="left_arrows-circle"
                className="menu-tool-btn"
                @click="handleFold()"
              />

              <svg-icon
                v-if="expendTree"
                icon-class="up_circle"
                className="menu-tool-btn"
                @click="expandCollapseTree()"
              />
              <svg-icon
                v-if="!expendTree"
                icon-class="down-circle"
                className="menu-tool-btn"
                @click="expandCollapseTree()"
              />
              <svg-icon
                icon-class="search-circle_1"
                className="menu-tool-btn"
                @click="getTreeSelect()"
              />
            </div>
          </div>
          <div class="head-container">
            <el-tree
              ref="tree"
              :data="leftTreeData"
              :props="defaultProps"
              node-key="id"
              :load="loadNode"
              lazy
              @node-click="handleNodeClick"
              :render-content="renderContent"
            />
          </div>
        </div>
        <div class="fold-btn" v-show="!leftSide">
          <div @click="handleFold()">
            <svg-icon
              v-if="!leftSide"
              icon-class="right_arrows_circle"
              className="menu-tool-btn"
            />
          </div>
        </div>
      </div>
      <div :style="{ width: rightTableWidth + '%' }" class="right-table">
        <div class="app-container">
          <Ht-search-form
            :advOptions="[]"
            :dictMap="dictMapAsync"
            :searchExtend="extendSearch"
            :formOptions="formOptions"
            :queryParams="queryParams"
            :outputQueryParams="queryParams"
            permission="user:deptInfo:view"
          ></Ht-search-form>
          <ht-table
            ref="dataTable"
            :dictMap="dictMap"
            :opButtonList="opButtonList"
            :queryParams="queryParams"
            :reqConfig="reqConfig"
            :tableBindColumns="tableBindColumns"
            :extendColumns="extendColumns"
          >
            <template v-slot:operate>
              <el-table-column
                align="left"
                label="操作"
                width="160"
                fixed="right"
              >
                <template slot-scope="scope">
                  <ht-button-group
                    :buttonList="[
                      {
                        label: '编辑',
                        permission: 'user:deptInfo:edit',
                        doFunc: () => {
                          handleUpdate(scope.row);
                        },
                      },
                      {
                        label: '新增',
                        visible: scope.row.status === 1,
                        permission: 'user:deptInfo:add',
                        doFunc: () => {
                          handleAdd(scope.row);
                        },
                      },
                      {
                        label: '机构迁移',
                        permission: 'user:deptInfo:edit',
                        doFunc: () => {
                          handleDeptMove(scope.row);
                        },
                      },
                      {
                        label: '删除',
                        visible: scope.row.status === 1,
                        permission: 'user:deptInfo:remove',
                        doFunc: () => {
                          handleDelete(scope.row);
                        },
                      },
                    ]"
                  />
                </template>
              </el-table-column>
            </template>
          </ht-table>
        </div>

        <!-- 添加或修改弹出框 -->
        <add-update
          ref="editDeptDialog"
          :checkMenu="checkMenu"
          :extendParams="extendColumns"
          @editComplete="changeOpen"
        ></add-update>

        <!-- 机构迁移 -->
        <div v-if="open1">
          <dept-move
            :addForm="addForm"
            :checkMenu="checkMenu"
            :deptId="deptId"
            :funcParams="funcParams"
            :open="open1"
            :statusOptions="statusOptions"
            :title="title"
            @changeOpen="changeOpen1"
            @submitAddForm="submitAddForm"
          ></dept-move>
        </div>
        <!-- 导出文件组建 -->
        <ht-export-file
          ref="exportFile"
          :columnList="exportColumns"
          :justAsync="true"
          :exportParams="exportParams"
          :exportFun="exportFun"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  apiUrlConfig,
  indexInit,
  delDeptInfo,
  tenantDeptTree,
  addDeptInfo,
  updateDeptInfo,
  exportAll,
  deptSelectTreeForClick,
  deptSelectTree,
} from "@/api/authority_app/deptInfo/deptInfo";
import AddUpdate from "./addUpdate";
import deptMove from "./deptMove";
import { listPageMixin } from "@/libs/listPageMixin";
import { mapGetters } from "vuex";
import _ from "lodash";
import { baseUrlConfig } from "@/api/authority_app/base";

export default {
  name: "DeptInfo",
  components: {
    AddUpdate,
    deptMove,
  },
  computed: {
    ...mapGetters(["admin"]),
  },
  mixins: [listPageMixin],
  data() {
    return {
      extendParentKey: 2,
      loading: false,
      leftSide: true,
      leftSideWidth: 20,
      overflowX: "auto",
      rightTableWidth: 80,
      expendTree: false,
      reqConfig: apiUrlConfig,
      leftTreeData: [],
      nodeKey: ["code"],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: "isLeaf",
      },
      exportColumns: [],
      opButtonList: () => {
        return [
          {
            label: "新增",
            type: "primary",
            icon: "el-icon-plus",
            permission: "user:deptInfo:add",
            actionType: "add",
            clickFun: () => {
              this.handleAdd();
            },
          },
          /*{
            label: "导出全部",
            type: "warning",
            icon: "el-icon-plus",
            permission: "user:deptInfo:add",
            actionType: "export",
            clickFun: () => {
              this.exportAll();
            },
          },*/
/*          {
            label: "导入",
            type: "success",
            icon: "el-icon-upload",
            actionType: "import",
          },*/
        ];
      },
      //弹出层标题
      title: "",
      // 是否超管
      isAdmin: false,
      // 租户数据
      tenantOptions: [],
      //选中的树节点Id
      checkMenu: [],
      // 组织状态数据字典
      statusOptions: [],
      //新增编辑dialog是否展示
      open1: false,
      // 查询参数
      queryParams: {
        tenantId: "",
        deptName: "",
        status: "",
        nodeId: "",
        deptCode: "",
        nodeType: "",
      },
      //function参数
      funcParams: {
        deptCode: "",
        tenantCode: "",
        name: "",
        userId: "",
        deptId: "",
      },
      // 查询结果
      dataList: [],
      flag: false,
      refreshTable: true,
      addForm: {
        id: "",
        parentCode: "",
        parentId: "",
        deptCode: "",
        deptName: "",
        orderNum: "",
        leader: "",
        phone: "",
        deptLevel: "",
        email: "",
        parentName: "",
        expandValueInfoMap: {},
      },
      deptId: "",
      disabled: true,
      // 列信息
      tableBindColumns: [
        { label: `一级机构ID`, prop: "rootDeptId", visible: false },
        { label: `一级机构编号`, prop: "rootDeptCode", visible: false },
        { label: `组织机构Id`, prop: "id", visible: false },
        { label: `组织名称`, prop: "deptName" },
        { label: `组织编号`, prop: "deptCode" },
        { label: `租户编号`, prop: "tenantCode" },
        { label: `负责人`, prop: "leader", visible: false },
        { label: `排序`, prop: "orderNum" },
        {
          label: `状态`,
          prop: "status",
          dictCode: "sys_normal_disable",
        },
        { label: `创建时间`, prop: "createTime", width: "180" },
      ],
      searchExtendColumns: [],
      showExtendSearch: false, // 是否展示高级搜索
      extendParamsDict: {}, // 扩展字段的字典数据
      formOptions: [],
      searchFormDictList: ["sys_normal_disable"],
      dictMapAsync: {},
    };
  },
  watch: {
    extendColumns: {
      handler(data) {
        this.exportColumns = this.tableBindColumns.concat(data);
      },
    },
  },
  async mounted() {
    const formOptions = [
      {
        type: "input",
        prop: "deptName",
        defaultAttr: {
          size: "small",
          label: "组织名称",
          placeholder: "请输入组织名称",
        },
      },
      {
        type: "input",
        prop: "deptCode",
        defaultAttr: {
          size: "small",
          label: "组织编号",
          placeholder: "请输入组织编号",
        },
      },
      {
        type: "dict",
        prop: "status",
        dict: "sys_normal_disable",
        defaultAttr: {
          size: "small",
          label: "组织状态",
          placeholder: "请选择组织状态",
        },
      },
    ];
    // const {result} = await indexInit();
    // this.$set(formOptions[0], "selectOptionList", result.tenants);
    this.formOptions = formOptions;
    this.dictMapAsync = this.getDictMap();
  },
  created() {
    this.reqConfig.uploadUrl = baseUrlConfig.uploadUrlForUser;
    this.getTreeSelect();
    indexInit().then((response) => {
      this.isAdmin = response.result.isAdmin;
      this.tenantOptions = response.result.tenants;
    });
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.result;
    });
    this.exportColumns = this.tableBindColumns;
  },
  methods: {
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
        </span>
      );
    },
    /** 收缩框按钮 */
    handleFold() {
      this.leftSide = !this.leftSide;
      if (this.leftSide) {
        this.leftSideWidth = "20%";
        this.rightTableWidth = 80;
      } else {
        this.leftSideWidth = "36px";
        this.rightTableWidth = 100;
      }
    },
    /** 展开收缩树 */
    expandCollapseTree() {
      this.expendTree = !this.expendTree;
      setTimeout(() => {
        for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
          this.$refs.tree.store._getAllNodes()[i].expanded = this.expendTree;
        }
      }, 100);
    },
    getTreeSelect() {
      deptSelectTree(this.searchName, !this.admin).then((res) => {
        if (res.result && res.result.length > 0) {
          this.leftTreeData = res.result;
        }
      });
    },
    /** 树 点击 事件 */
    handleNodeClick(data) {
      if (data.disabled) {
        return;
      }
      this.$set(this.queryParams, "nodeId", data.id);
      this.$set(this.queryParams, "nodeType", data.nodeType);
      this.$nextTick(() => {
        this.doQuery();
      });
    },
    loadNode(node, resolve) {
      // 如果是根节点
      if (node.childNodes && node.childNodes.length > 0) {
        if (node.data.children && node.data.children.length > 0) {
          resolve(
            node.data.children.map((item) => {
              return {
                ...item,
                leaf: item.isLeaf,
              };
            })
          );
          return;
        } else {
          deptSelectTreeForClick(node.data.code, "", node.data.nodeType).then(
            (res) => {
              resolve(
                res.result.map((item) => {
                  for (let co of this.selectDataList) {
                    if (co[this.nodeKey] == item[this.nodeKey]) {
                      item.checked = true;
                    }
                  }
                  return {
                    ...item,
                    leaf: item.isLeaf,
                  };
                })
              );
            }
          );
        }
      } else {
        if (node.data[this.nodeKey] && !node.data.isLeaf) {
          if (node.data.children && node.data.children.length > 0) {
            resolve(
              node.data.children.map((item) => {
                return {
                  ...item,
                  leaf: item.isLeaf,
                };
              })
            );
            return;
          }
          deptSelectTreeForClick(node.data.code, "", node.data.nodeType).then(
            (res) => {
              resolve(
                res.result.map((item) => {
                  return {
                    ...item,
                    leaf: item.isLeaf,
                  };
                })
              );
            }
          );
        } else {
          resolve([]);
        }
      }
    },
    /** 字典状态字典翻译 */
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    //新增组织机构
    handleAdd(row) {
      this.$refs.editDeptDialog.show(
        "",
        false,
        row ? row.deptCode : "",
        row ? row.tenantCode : "",
        false
      );
    },
    //重置
    reset() {
      this.$set(this, "addForm", {
        id: "",
        parentId: "",
        deptCode: "",
        deptName: "",
        orderNum: "",
        leader: "",
        phone: "",
        deptLevel: "",
        email: "",
        status: "1",
        expandValueInfoMap: {},
      });
      this.resetForm("addForm");
    },
    //修改组织机构
    handleUpdate(row) {
      this.$refs.editDeptDialog.show(
        row.id,
        true,
        row ? row.parentCode : "",
        row ? row.tenantCode : "",
        row ? row.parentId == "0" : false
      );
    },
    //机构迁移
    handleDeptMove(row) {
      this.checkMenu = [];
      this.open1 = true;
      this.title = "组织机构迁移";
      this.$set(this, "addForm", _.clone(row));
      // this.addForm.parentId = row.parentId;
      // this.addForm.deptCode = row.deptCode;
      // this.addForm.deptName = row.deptName;
      // this.addForm.deptLevel = row.deptLevel;
      // this.addForm.status = row.status + "";
      // this.addForm.parentCode = row.parentCode;
      this.funcParams.deptId = row.id;
      this.funcParams.deptCode = row.deptCode;
      this.funcParams.tenantCode = row.tenantCode;
      var parentId = row.parentId;
      if (parentId === "0") {
        parentId = row.tenantId;
      }
      this.checkMenu.push(parentId);
    },
    //删除组织机构
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$confirm("是否确认删除组织机构数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delDeptInfo(id);
        })
        .then(() => {
          this.doQuery();
          this.msgSuccess("删除成功");
        })
        .catch((action) => {});
    },
    //加载查询方法
    queryFormDeptTreeReq() {
      var deptCode = this.funcParams.deptCode;
      var tenantCode = this.funcParams.tenantCode;
      var name = this.funcParams.name;
      var userId = this.funcParams.userId;
      var deptId = this.funcParams.deptId;
      return tenantDeptTree(userId, deptId, deptCode, tenantCode, name);
    },
    //属性组件选择后的回调
    // selectChange(dataArray) {
    //   let ids = dataArray.map(item => item.id);
    //   this.addForm.parentId = ids.join(',')
    //   this.checkMenu = ids;
    // },
    //一级弹窗状态修改
    changeOpen(state) {
      if (state) {
        // 刷新左侧树
        this.getTreeSelect();
        this.doQuery();
        this.reset();
      }
    },
    changeOpen1(open1) {
      this.open1 = open1;
      if (!this.open1) {
        // 刷新左侧树
        this.getTreeSelect();
        this.doQuery();
        this.reset();
      }
    },
    //新增\编辑提交接口
    submitAddForm(data) {
      delete this.addForm.createTime;
      delete this.addForm.updateTime;
      if (this.addForm.id !== undefined && this.addForm.id !== "") {
        updateDeptInfo(this.addForm).then((response) => {
          this.msgSuccess("修改成功");
          this.changeOpen(false);
          this.changeOpen1(false);
        });
      } else {
        addDeptInfo(this.addForm).then((response) => {
          this.msgSuccess("新增成功");
          this.changeOpen(false);
          this.changeOpen1(false);
        });
      }
    },
    changeShowExtendSearch(state) {
      this.$nextTick((res) => {
        this.$refs.htExtendSearch.changeShowState(state);
      });
    },
    exportFun(exportJson) {
      return exportAll(exportJson, {
        current: 1,
        limit: 10,
      });
    },
    exportAll() {
      this.$refs.exportFile.show();
      // exportAll().then(res => {
      //   window.location.href = `/authority-app/s/common/tempDownload?fileId=${res.result}&HTtoken=${getTokenForCookie()}`
      // })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables.scss";

.left-side {
  margin-right: 5px;
  display: flex;
  justify-content: space-between;
  overflow: auto;
  width: 220px;
  padding-bottom: 40px;
  .menu-tree {
    width: 100%;
    height: 100%;
    padding: 16px 0 30px 16px;
  }

  .fold-btn {
    width: 100%;
    padding: 16px 8px;
  }

  .nav {
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    padding-right: 10px;
    padding-bottom: 10px;
    .tit-txt {
      font-weight: 600;
    }
  }
  .head-container {
    height: 100%;
    overflow: auto;
    ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
      display: inline;
    }
  }
}

.right-table {
  min-width: 82%;
  max-width: 100%;
  padding-top: 16px;
  border-left: 1px solid #e7e7e7;
}

.app-container-cust {
  background-color: #ffffff;
  height: calc(100% - 24px);
  padding-bottom: 0;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  border-radius: 6px;
  -webkit-box-shadow: 0px 2px 3px #0000001a;
  box-shadow: 0px 2px 3px #0000001a;
}
.app-container {
  padding-top: 0px !important;
}
.menu-tool-btn {
  width: 24px;
  height: 24px;
}
</style>
